package com.simpleaccount.Add;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.simpleaccount.Cloud.CloudOperations;
import com.simpleaccount.Db.DbUtils;
import com.simpleaccount.Entity.Entry;
import com.simpleaccount.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 超 on 2017/7/12.
 */


public class AddActivity extends FragmentActivity implements IncomeFragment.Callback, OutcomeFragment.Callback {
    @Bind(R.id.tv_back)
    ImageView tvAddBack;
    //    @Bind(R.id.tv_title)
//    TextView tvAddTitle;
    @Bind(R.id.tv_outcome)
    TextView tvOutcome;
    @Bind(R.id.tv_income)
    TextView tvIncome;
    @Bind(R.id.tv_number)
    TextView tvNumber;
    @Bind(R.id.fragment_accounting)
    LinearLayout fragmentAccounting;
    @Bind(R.id.number1)
    TextView number1;
    @Bind(R.id.number4)
    TextView number4;
    @Bind(R.id.number7)
    TextView number7;
    @Bind(R.id.reset)
    TextView reset;
    @Bind(R.id.number2)
    TextView number2;
    @Bind(R.id.number5)
    TextView number5;
    @Bind(R.id.number8)
    TextView number8;
    @Bind(R.id.number0)
    TextView number0;
    @Bind(R.id.number3)
    TextView number3;
    @Bind(R.id.number6)
    TextView number6;
    @Bind(R.id.number9)
    TextView number9;
    @Bind(R.id.point)
    TextView point;
    @Bind(R.id.add)
    TextView add;
    @Bind(R.id.minus)
    TextView minus;
    @Bind(R.id.ok)
    TextView ok;
    @Bind(R.id.tv_add_date)
    TextView tvAddDate;
    @Bind(R.id.et_msg)
    EditText etMsg;
    @Bind(R.id.iv_submit)
    ImageView ivSubmit;
    @Bind(R.id.ll_numberbackgroundcolor)
    LinearLayout llNumberbackgroundcolor;
    @Bind(R.id.ll_calculator)
    LinearLayout llCalculator;
    private List<Double> value_list = new ArrayList<Double>();// 存用户输入的数字
    private List<Integer> operator_list = new ArrayList<Integer>();// 存用户输入的运算符，定义+为0，-为1，×为2，÷为3
    // 状态记录
    private boolean add_flag = false;// +按下
    private boolean minus_flag = false;// -按下
    private boolean multi_flag = false;// ×按下
    private boolean div_flag = false;// ÷按下
    private boolean result_flag = false;// =按下
    private boolean can_operate_flag = false;// 按下=是否响应
    private IncomeFragment fmIncome;
    private OutcomeFragment fmPay;
    private FragmentManager fManager;

    public String category;
    private String categoryToDB;
    private CalendarDay calendarDay;
    Date date = Calendar.getInstance().getTime();
    Entry entry;
    String number;
    String remark;
    double number_new;
    String remark_new;

    public void setDate() {

        tvAddDate.setText(String.valueOf(new SimpleDateFormat("yyyy-M-d", Locale.CHINA).format(calendarDay.getDate())));
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        ButterKnife.bind(this);
        if (getIntent().getSerializableExtra("entry") != null) {
            entry = (Entry) getIntent().getSerializableExtra("entry");
            number = String.format(Locale.CHINA, "%.2f", entry.getMoney());
            remark = entry.getMsg();
            tvNumber.setText(number);
            etMsg.setText(remark);

            //llNumberbackgroundcolor.setBackgroundColor(DbUtils.getCategory(entry.getCategory()).getColor());
            calendarDay = new CalendarDay(date);
            tvAddDate.setText(String.valueOf(new SimpleDateFormat("yyyy-M-d", Locale.CHINA).format(entry.getDate())));

        } else {
            calendarDay = new CalendarDay(date);
            tvAddDate.setText(String.valueOf(new SimpleDateFormat("yyyy-M-d", Locale.CHINA).format(Calendar.getInstance().getTime())));
        }
        initView();
        clickMenu(0);


        //initView();

}


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        fManager = getSupportFragmentManager();
    }

    public void clickMenu(int vID) {
        FragmentTransaction trans = fManager.beginTransaction();
        hideFragment(trans);
        setFragment(vID, trans);

        trans.commit();
        if (vID == 0) {
            tvOutcome.setTextColor(getResources().getColor(R.color.杜若色));
            tvIncome.setTextColor(getResources().getColor(R.color.灰色));
//            fmPay.onclicked("一般");
             llNumberbackgroundcolor.setBackgroundColor(DbUtils.getCategory("一般").getColor());
            if (getIntent().getSerializableExtra("entry") != null) {
                llNumberbackgroundcolor.setBackgroundColor(DbUtils.getCategory(entry.getCategory()).getColor());
            }
        }
        if (vID == 1) {
            tvIncome.setTextColor(getResources().getColor(R.color.杜若色));
            tvOutcome.setTextColor(getResources().getColor(R.color.灰色));
            llNumberbackgroundcolor.setBackgroundColor(DbUtils.getCategory("普通").getColor());
            //fmIncome.onclicked("普通");
            if (getIntent().getSerializableExtra("entry") != null) {
                llNumberbackgroundcolor.setBackgroundColor(DbUtils.getCategory(entry.getCategory()).getColor());
            }
        }
    }

    public void hideFragment(FragmentTransaction trans) {
        if (null != fmIncome) {
            trans.hide(fmIncome);
        }
        if (null != fmPay) {
            trans.hide(fmPay);
        }
    }

    private void setFragment(int vid, FragmentTransaction trans) {
        switch (vid) {
            case 0:
                if (null == fmPay) {
                    fmPay = new OutcomeFragment();
                    trans.add(R.id.fragment_accounting, fmPay);
                    //fmPay.onclicked("一般");
                } else {
                    trans.show(fmPay);
                    //fmPay.onclicked("一般");

                }
                break;
            case 1:
                if (null == fmIncome) {
                    fmIncome = new IncomeFragment();
                    trans.add(R.id.fragment_accounting, fmIncome);
                    //fmIncome.onclicked("普通");
                } else {
                    trans.show(fmIncome);
                    //fmIncome.onclicked("普通");
                }
                break;
            default:
                break;
        }
    }

    public void clickback() {
        Intent intent = getIntent();
        setResult(-1, intent);
        finish();
    }


    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        setResult(-1, intent);
        finish();
    }

    private void num_down(String num) {
        if (add_flag || minus_flag || multi_flag || div_flag || result_flag) {
            if (result_flag)// 按下等号，刚刚算完一个运算的状态
            {
                //textView1.setText("");
            }
            tvNumber.setText("");// 如果用户刚刚输入完一个运算符
            add_flag = false;
            minus_flag = false;
            multi_flag = false;
            div_flag = false;
            result_flag = false;
        }
        if ((num.equals(".") && tvNumber.getText().toString().indexOf(".") < 0)
                || !num.equals(".")) {
            // 如果用户输入的是小数点.，则要判断当前已输入的数字中是否含有小数点.才允许输入
            tvNumber.setText(tvNumber.getText() + num);
            //textView1.setText(textView1.getText() + num);
            can_operate_flag = true;
        }
    }

    @OnClick({R.id.iv_submit, R.id.tv_outcome, R.id.tv_income, R.id.tv_back, R.id.number1, R.id.number4, R.id.number7, R.id.reset, R.id.number2, R.id.number5, R.id.number8, R.id.number0, R.id.number3, R.id.number6, R.id.number9, R.id.point, R.id.add, R.id.minus, R.id.ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_outcome:
                clickMenu(0);
                break;
            case R.id.tv_income:
                clickMenu(1);
                break;
            case R.id.tv_back:
                clickback();
                break;
            case R.id.number1:
                num_down("1");
                break;
            case R.id.number4:
                num_down("4");
                break;
            case R.id.number7:
                num_down("7");
                break;
            case R.id.reset:
                operator_list.clear();
                value_list.clear();
                add_flag = false;
                minus_flag = false;
                multi_flag = false;
                div_flag = false;
                result_flag = false;
                can_operate_flag = false;
                tvNumber.setText("");
                //textView1.setText("");
                break;
            case R.id.number2:
                num_down("2");
                break;
            case R.id.number5:
                num_down("5");
                break;
            case R.id.number8:
                num_down("8");
                break;
            case R.id.number0:
                num_down("0");
                break;
            case R.id.number3:
                num_down("3");
                break;
            case R.id.number6:
                num_down("6");
                break;
            case R.id.number9:
                num_down("9");
                break;
            case R.id.add:
                if (!add_flag)// 防止用户多次输入一个符号键，符号键只允许输入一次
                {
                    result_flag = false;
                    value_list.add(Double.parseDouble(tvNumber.getText()
                            .toString()));// 将当前已输入的数字放入value_list
                    operator_list.add(0);
                    //textView1.setText(textView1.getText() + "+");
                    add_flag = true;
                    can_operate_flag = false;// 刚刚输入完符号，不能构成一条正常的表达式，如111+，设置为不可运行状态
                }
                break;
            case R.id.minus:
                if (!minus_flag) {
                    result_flag = false;
                    value_list.add(Double.parseDouble(tvNumber.getText()
                            .toString()));
                    operator_list.add(1);
                    //textView1.setText(textView1.getText() + "-");
                    minus_flag = true;
                    can_operate_flag = false;
                }
                break;
            case R.id.ok:
                if (value_list.size() > 0 && operator_list.size() > 0
                        && can_operate_flag) {// 需要防止用户没输入数字，或者只输入了一个数，就按=。
                    value_list.add(Double.parseDouble(tvNumber.getText()
                            .toString()));
                    double total = value_list.get(0);
                    for (int i = 0; i < operator_list.size(); i++) {
                        int _operator = operator_list.get(i);// operator是C#的运算符重载的关键字，前面加个_来区别
                        switch (_operator) {
                            case 0:
                                total += value_list.get(i + 1);
                                break;
                            case 1:
                                total -= value_list.get(i + 1);
                                break;
                            case 2:
                                total *= value_list.get(i + 1);
                                break;
                            case 3:
                                total /= value_list.get(i + 1);
                                break;
                        }
                    }
                    tvNumber.setText(total + "");
                    //textView1.setText(total + "");
                    operator_list.clear();// 算完，就清空累积数字与运算数组
                    value_list.clear();
                    result_flag = true;// 表示=按下
                }

                break;
            case R.id.point:
                num_down(".");
                break;
            case R.id.iv_submit:
                if (getIntent().getSerializableExtra("entry") == null) {
                    submit();
                } else if (getIntent().getSerializableExtra("entry") != null) {
                    modify();
                }
                break;
        }
    }


    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    @OnClick(R.id.tv_add_date)
    public void onViewClicked() {
        View popupView = AddActivity.this.getLayoutInflater().inflate(R.layout.popupwindow, null);
        MaterialCalendarView calendarView = (MaterialCalendarView) popupView.findViewById(R.id.calendarView);

        calendarView.setSelectedDate(calendarDay);


        // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。


        // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
        final PopupWindow window = new PopupWindow(popupView, 400, 900);
        // 设置弹出窗体的宽和高
        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                calendarDay = date;
                setDate();
                window.dismiss();

            }
        });
        window.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        window.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        // TODO: 2016/5/17 设置动画
        window.setAnimationStyle(R.style.popwindow_anim);
        // TODO: 2016/5/17 设置背景颜色
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        // TODO: 2016/5/17 设置可以获取焦点
        window.setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
        // TODO：更新popupwindow的状态
        window.update();
        // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
        //window.showAsDropDown(tvAddBack, 0, 20);
        window.showAtLocation(findViewById(R.id.tv_add_date), Gravity.BOTTOM, 0, 0);

        backgroundAlpha(0.5f);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

    }

    @Override
    public void getCategory(String category) {
        categoryToDB = category;
    }


    public void submit() {
        Double money;
        if (null != fmPay || fmIncome.isHidden()) {
            fmPay.setCategory(this);
        }
        if (null != fmIncome || fmPay.isHidden()) {
            fmIncome.setCategory(this);
        }
        if (tvNumber.getText().toString().equals("")   )
        {
            money=0.0;
        }
        else{
            money = Double.valueOf(tvNumber.getText().toString());
            money = -money;
        }

        if (categoryToDB.equals("普通") ||
                categoryToDB.equals("工资") ||
                categoryToDB.equals("奖金") ||
                categoryToDB.equals("生活费") ||
                categoryToDB.equals("兼职") ||
                categoryToDB.equals("红包")) {
            money = -money;
        }
        String msg = etMsg.getText().toString();
        date = calendarDay.getDate();
        Entry entry = new Entry(DbUtils.getCount()+1, money, DbUtils.getCategory(categoryToDB), date, msg);
        DbUtils.insertEntry(entry);
        CloudOperations.singleUpload(entry.getId(), AddActivity.this );


        finish();
    }

    public void modify() {
        if (null != fmPay || fmIncome.isHidden()) {
            fmPay.setCategory(this);
        }
        if (null != fmIncome || fmPay.isHidden()) {
            fmIncome.setCategory(this);
        }
        number_new = Double.valueOf(tvNumber.getText().toString());
        if (categoryToDB.equals("普通") ||
                categoryToDB.equals("工资") ||
                categoryToDB.equals("奖金") ||
                categoryToDB.equals("生活费") ||
                categoryToDB.equals("兼职") ||
                categoryToDB.equals("红包")) {
            number_new = -number_new;
        }
        date = calendarDay.getDate();
        remark_new = etMsg.getText().toString();
        Entry entry_new = new Entry(entry.getId(), number_new, DbUtils.getCategory(categoryToDB), date, remark_new);
        DbUtils.modifyEntry(entry_new);
        Intent intent = getIntent();
        setResult(0, intent);
        finish();
    }

}
